package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import com.alibaba.fastjson.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 工单查询API
 */

public class apiWoBackSend implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiWoBackSend.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        // 初始化返回参数
        JSONObject result = new JSONObject();

        JSONObject resultJson = null;
        //接收客户端调用参数
        String callJson = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }

        log.info("[调用请求信息]:" + callJson);

        try {
            //解析Json
            JSONObject inJson = JSONObject.parseObject(callJson);

            //获取页面信息参数
            String in_s_objetive_guid = inJson.getJSONObject("data").getString("in_s_objetive_guid"); //当前objective_guid
            String in_s_elitetask_guid = inJson.getJSONObject("data").getString("in_s_elitetask_guid"); //当前elitetask_guid
            String in_back_send_type= inJson.getJSONObject("data").getString("in_back_send_type"); //退单下送类型
            String in_objectivesubstatus= inJson.getJSONObject("data").getString("in_objectivesubstatus"); //当前工单操作类型

            String in_auto_sendto = inJson.getJSONObject("data").getString("in_auto_sendto"); //根据档位自动匹配到的组大白菜组id
            String in_auto_send_group = inJson.getJSONObject("data").getString("in_auto_send_group"); //多任务节点存在业务部自动下送至档位匹配到的组别
            String in_map_roleid = inJson.getJSONObject("data").getString("in_map_roleid"); //当前工单可操作的角色

            String in_r_send_group = '';//工单下送组别
            String in_r_send_staff = '';//工单下送staff
            String in_r_send_node = '';//工单下送nodeid

            String in_operation_type = 'SENDNS';

            String in_cur_expiredlen = '0';
            String in_cur_expiredflag = '0';

            String queryWorkOrderSQL = "select back_node as from_back_node,back_group as from_back_group,back_staff as from_back_staff ," +
                    "handleby_id as oldstaff_id,handlegroup_id as oldhandlegroup_id,map_id as r_map_id,curstep_id_map as r_node_id ,comments ," +
                    " sysdate() as modifieddate ,flowdetail ,customer_guid " +
                    "from elitetask where elitetask_guid = '" + in_s_elitetask_guid + "' limit 1";
            log.debug("执行任务数据查询SQL:" + queryWorkOrderSQL);
            List WorkOrderInfo = eliteBean.chaxun_sql(queryWorkOrderSQL, "dataSource");

            String in_r_map_id = WorkOrderInfo.get(0).get("r_map_id");//当前mapid
            String in_r_node_id = WorkOrderInfo.get(0).get("r_node_id");//当前nodeid
            String in_oldhandlegroup_id = WorkOrderInfo.get(0).get("oldhandlegroup_id");//当前组别
            String in_oldstaff_id = WorkOrderInfo.get(0).get("oldstaff_id");//当前staff
            String in_wostepcomments = WorkOrderInfo.get(0).get("comments");
            String in_modifieddate = WorkOrderInfo.get(0).get("modifieddate");
            String in_workorderflowdetail = WorkOrderInfo.get(0).get("flowdetail");
            String in_s_customer_guid = WorkOrderInfo.get(0).get("customer_guid");

            String in_r_from_back_node = WorkOrderInfo.get(0).get("from_back_node");//从哪个节点退单的
            String in_r_from_back_group = WorkOrderInfo.get(0).get("from_back_group");//从哪个组别退单的
            String in_r_from_back_staff = WorkOrderInfo.get(0).get("from_back_staff");//从哪个staff退单的

            log.debug("工单待处理数据："+in_r_map_id + "&&" + in_r_node_id + "&&" + in_oldhandlegroup_id + "&&" + in_oldstaff_id+ "&&" + in_wostepcomments+ "&&" + in_modifieddate+ "&&" + in_workorderflowdetail);
            log.debug("工单待处理数据："+in_s_customer_guid + "&&" + in_r_from_back_node + "&&" + in_r_from_back_group + "&&" + in_r_from_back_staff);

            String queryWorkSendSQL = "select e1.extendvalue as sendgr,e2.extendvalue as sendsf,e3.extendvalue as sendnode ,e4.extendvalue as maintask_flag " +
            "from wo3_node_map n " +
            "left join wo3_nodemap_extend e1 ON n.map_id = e1.map_id AND n.nodemap_id = e1.nodemap_id and e1.extendid = 'SENDGR' " +
            "left join wo3_nodemap_extend e2 ON n.map_id = e2.map_id AND n.nodemap_id = e2.nodemap_id and e2.extendid = 'SENDSF' " +
            "left join wo3_nodemap_extend e3 ON n.map_id = e3.map_id AND n.nodemap_id = e3.nodemap_id and e3.extendid = 'SENDNODE' " +
            "left join wo3_nodemap_extend e4 ON n.map_id = e4.map_id AND n.nodemap_id = e4.nodemap_id and e4.extendid = 'MAINTASK' " +
            "where n.map_id = '" + in_r_map_id + "'and n.nodemap_id = '" + in_r_node_id + "'limit 1";
            log.debug("执行任务数据查询SQL:" + queryWorkSendSQL);
            List WorkSendInfo = eliteBean.chaxun_sql(queryWorkSendSQL, "dataSource");

            String in_r_next_step_node = WorkSendInfo.get(0).get("sendnode");//当前节点的下步节点
            String in_r_next_step_group = WorkSendInfo.get(0).get("sendgr");//当前节点的下步组别
            String in_r_next_step_staff = WorkSendInfo.get(0).get("sendsf");//当前节点的下步staff
            String in_maintask_flag = WorkSendInfo.get(0).get("maintask_flag");//当前节点是否为多任务
            log.debug("工单流程下送数据：" + in_r_next_step_node + "&&" + in_r_next_step_group + "&&" + in_r_next_step_staff + "&&" + in_maintask_flag);
            log.debug("工单处理类型：" + in_back_send_type);

            //退单下送原处理人处理逻辑
            if(in_back_send_type == 'CONTINUE_DEAL')
            {
                in_r_send_node = in_r_from_back_node;//工单下送nodeid
                in_r_send_group = in_r_from_back_group;//工单下送组别
                in_r_send_staff = in_r_from_back_staff;//工单下送staff


            }else if(in_back_send_type == 'RESTART_DEAL') //退单后选择重新开始处理逻辑
            {
                in_r_send_node = in_r_next_step_node;//工单下送nodeid
                in_r_send_group = in_r_next_step_group;//工单下送组别
                in_r_send_staff = in_r_next_step_staff;//工单下送staff

            };
            log.debug("工单下送信息：" + in_r_send_node + "&&" + in_r_send_group + "&&" + in_r_send_staff);
            log.debug("工单信息：" + in_s_elitetask_guid + "&&" + in_s_objetive_guid);

            if(in_back_send_type == 'CONTINUE_DEAL')
            {
                String[] data = new String[4];
                //插入步骤信息表
                data[0] = "insert into workorderstep3(workorderstep_guid,workorder_guid,oldhandleby_id,oldhandlegroup_id,handleby_id,handlegroup_id,workorderstepstatus,comments," +
                        "modifieddate,from_stepidmap,to_stepidmap,stepexpired,stepstart,cur_expiredlen,cur_expiredflag,workstarttime,workendtime) " +
                        "values (uuid(), '" + in_s_objetive_guid + "','" + in_oldstaff_id + "','" + in_oldhandlegroup_id + "','" + in_r_send_staff + "','" + in_r_send_group + "','" + in_operation_type + "','" + in_wostepcomments + "','" +
                        in_modifieddate + "','" + in_r_node_id + "','" + in_r_send_node + "','" + in_modifieddate + "','" + in_modifieddate + "','" + in_cur_expiredlen + "','" + in_cur_expiredflag + "','" + in_modifieddate + "','" + in_modifieddate + "')";
                //插入工单路径数据
                data[1] = "insert into workorderpath3(workorderpath_guid,workorder_guid,handlegroup,handleby,modifieddate,woframe_id,from_stepidmap,to_stepidmap)"+
                        "values (uuid(), '" + in_s_objetive_guid + "','" + in_r_send_group + "','" + in_r_send_staff + "','" + in_modifieddate + "','" + in_r_map_id + "','" + in_r_node_id + "','" + in_r_send_node+"')";
                //更新elitetask
                data[2] = "update elitetask set "+
                        "handleby_id = '" + in_r_send_staff +"',"+
                        "handlegroup_id = '" + in_r_send_group +"',"+
                        "objectivesubstatus = '" + in_objectivesubstatus +"',"+
                        "curstep_id = '" + in_r_send_node +"',"+
                        "curstep_id_map = '" + in_r_send_node +"',"+
                        "back_node = '',"+
                        "back_group = '',"+
                        "back_staff = ''"+
                        "where elitetask_guid = '"+ in_s_elitetask_guid + "' and objective_guid = '" + in_s_objetive_guid + "'";
                //更新objective
                data[3] = "update objective set " +
                        "handleby_id = '" + in_r_send_staff +"',"+
                        "handlegroup_id = '" + in_r_send_group +"',"+
                        "curstep_id_map = '" + in_r_send_node +"',"+
                        "objectivesubstatus = '" + in_objectivesubstatus +"' "+
                        "where objective_guid = '" + in_s_objetive_guid + "' ";

                log.debug("当前执行更新结果SQL:" + data.toString());
                def dataresult = eliteBean.updateBatch(data, 'dataSource');
                log.debug("当前执行更新结果SQL结果:" + dataresult.toString());

            }
            else if(in_back_send_type == 'RESTART_DEAL')
            {
                String[] data = new String[5];
                //插入步骤信息表
                data[0] = "insert into workorderstep3(workorderstep_guid,workorder_guid,oldhandleby_id,oldhandlegroup_id,handleby_id,handlegroup_id,workorderstepstatus,comments," +
                        "modifieddate,from_stepidmap,to_stepidmap,stepexpired,stepstart,cur_expiredlen,cur_expiredflag,workstarttime,workendtime) " +
                        "values (uuid(), '" + in_s_objetive_guid + "','" + in_oldstaff_id + "','" + in_oldhandlegroup_id + "','" + in_r_send_staff + "','" + in_r_send_group + "','" + in_operation_type + "','" + in_wostepcomments + "','" +
                        in_modifieddate + "','" + in_r_node_id + "','" + in_r_send_node + "','" + in_modifieddate + "','" + in_modifieddate + "','" + in_cur_expiredlen + "','" + in_cur_expiredflag + "','" + in_modifieddate + "','" + in_modifieddate + "')";
                //插入工单路径数据
                data[1] = "insert into workorderpath3(workorderpath_guid,workorder_guid,handlegroup,handleby,modifieddate,woframe_id,from_stepidmap,to_stepidmap)"+
                        "values (uuid(), '" + in_s_objetive_guid + "','" + in_r_send_group + "','" + in_r_send_staff + "','" + in_modifieddate + "','" + in_r_map_id + "','" + in_r_node_id + "','" + in_r_send_node+"')";
                //更新elitetask
                data[2] = "update elitetask set "+
                        "handleby_id = '" + in_r_send_staff +"',"+
                        "handlegroup_id = '" + in_r_send_group +"',"+
                        "objectivesubstatus = '" + in_objectivesubstatus +"',"+
                        "curstep_id = '" + in_r_send_node +"',"+
                        "curstep_id_map = '" + in_r_send_node +"',"+
                        "back_node = '',"+
                        "back_group = '',"+
                        "back_staff = '' "+
                        "where elitetask_guid = '"+ in_s_elitetask_guid + "' and objective_guid = '" + in_s_objetive_guid + "'";
                //更新objective
                data[3] = "update objective set " +
                        "handleby_id = '" + in_r_send_staff + "',"+
                        "handlegroup_id = '" + in_r_send_group + "',"+
                        "curstep_id_map = '" + in_r_send_node + "',"+
                        "objectivesubstatus = '" + in_objectivesubstatus + "' "+
                        "where objective_guid = '" + in_s_objetive_guid + "' ";
                data[4] = "delete from elitetask where objective_guid = '" + in_s_objetive_guid + "' and elitetask_guid != '" + in_s_elitetask_guid + "'";
                log.debug("当前执行更新结果SQL:" + data.toString());
                def dataresult = eliteBean.updateBatch(data, 'dataSource');
                log.debug("当前执行更新结果SQL结果:" + dataresult.toString());

                if(in_maintask_flag=='DRW')//多任务处理逻辑
                {
                    String queryWorkTaskSQL = "SELECT n.nodemap_id as task_nod_id, e2.EXTENDVALUE as task_group_id, e3.EXTENDVALUE as task_staff_id,n.workorderframe_id as objectivetype_id " +
                            "FROM WO3_node_MAP n " +
                            "LEFT JOIN wo3_nodemap_extend   e1 ON n.map_id = e1.map_id AND n.nodemap_id = e1.nodemap_id " +
                            "left join wo3_nodemap_extend   e2 ON e1.nodemap_id = e2.nodemap_id and n.map_id = e2.map_id and e2.EXTENDID = 'TASKGR' " +
                            "left join wo3_nodemap_extend   e3 ON e1.nodemap_id = e3.nodemap_id and n.map_id = e3.map_id and e3.EXTENDID = 'TASKSF' " +
                            "WHERE 1=1 AND e1.EXTENDID = 'MAINTASK' " +
                            "AND e1.extendvalue ='" + in_r_node_id + "'" +
                            "and n.map_id ='" + in_r_map_id + "'";

                    log.debug("执行任务数据查询SQL:" + queryWorkTaskSQL);
                    List WorkTaskList = eliteBean.chaxun_sql(queryWorkTaskSQL, "dataSource");
                    //获取总行数
                    log.debug("执行工单查询数据SQL获取总条数:" + WorkTaskList.size());

                    for (int i = 0; i < WorkTaskList.size(); i++) {

                        String task_map_id = in_r_map_id;
                        Map selectResultcm = WorkTaskList.get(i);
                        String task_nod_id = selectResultcm.get("task_nod_id");
                        String task_group_id = selectResultcm.get("task_group_id");
                        String task_staff_id = selectResultcm.get("task_staff_id");
                        String objectivetype_id = selectResultcm.get("objectivetype_id");

                        log.debug("下送节点:" + task_nod_id);
                        log.debug("下送组别:" + task_group_id);
                        log.debug("下送人:" + task_staff_id);
                        if(task_group_id == 'AUTO')
                        {
                            //多任务节点存在业务部自动下送至档位匹配到的组别
                            task_group_id = in_auto_send_group;

                            String queryAutoSendSQL = "select srg.rolegroup_id as rolegroup_id,srg.staff_id as staff_id,sr.role_id as role_id " +
                            "from staffrole sr " +
                            "left join staff s on s.staff_id = sr.staff_id " +
                            "left join staffrolegroup srg on srg.staff_id = sr.staff_id " +
                            "where sr.role_id = '" + in_map_roleid + "' and srg.rolegroup_id = '" + in_auto_send_group + "'";
                            log.debug("执行任务数据查询SQL:" + queryAutoSendSQL);
                            List AutoSendList = eliteBean.chaxun_sql(queryAutoSendSQL, "dataSource");
                            for (int j = 0; j < AutoSendList.size(); j++) {
                                Map selectAutoSendResultcm = AutoSendList.get(j);
                                task_staff_id = selectAutoSendResultcm.get("staff_id");
                            }
                        }

                        data = new String[2];
                        //插入elitetask
                        data[0] = "insert into elitetask (elitetask_guid,objective_guid,objectivetype_id,expectstarttime,expectendtime,priority,handleby_id,handlegroup_id,createdby,createddate,modifiedby,modifieddate,currentexpectstarttime,comments,customer_guid,curstepstatus,curstep_id,flowdetail,curstep_id_map,map_id,objectivesubstatus,obflag,maintaskstep_id_map,back_node,back_group,back_staff) " +
                                "values(uuid(), '" + in_s_objetive_guid + "','" + objectivetype_id + "','" + in_modifieddate + "','" + in_modifieddate + "','NORMAL','" + task_staff_id +  "','" + task_group_id + "','" + in_oldstaff_id + "','" + in_modifieddate + "','" + in_oldstaff_id + "','" + in_modifieddate + "','" + in_modifieddate + "','" + in_wostepcomments + "','" + in_s_customer_guid + "','OPEN','" + task_nod_id + "','" +  in_workorderflowdetail + "','" + task_nod_id + "','" + task_map_id + "','" + in_objectivesubstatus + "','0',null,null,null,null)";
                        //插入工单路径数据
                        data[1] = "insert into workorderpath3(workorderpath_guid,workorder_guid,handlegroup,handleby,modifieddate,woframe_id,from_stepidmap,to_stepidmap)"+
                                "values (uuid(), '" + in_s_objetive_guid + "','" + task_group_id + "','" + task_staff_id + "','" + in_modifieddate + "','" + task_map_id + "','" + in_r_node_id + "','" + task_nod_id+"')";
                        log.debug("当前执行更新结果SQL:" + data.toString());
                        dataresult = eliteBean.updateBatch(data, 'dataSource');
                        log.debug("当前执行更新结果SQL结果:" + dataresult.toString());
                    }

                }
            }

            long endTime = System.currentTimeMillis();
            result.put("code", 1);
            result.put("msg", "处理完成、调用问题处理时长(毫秒):" + (endTime - startTime));

        } catch (Exception e) {
            result.put("code", 1008);
            result.put("msg", e.getMessage());
        }

        return result.toString();

    }
}